<?php
class MaoShen_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        // 实例化Zend_Acl
        $acl = new Zend_Acl();
        
        // 添加角色
        $acl->addRole('guest');
        $acl->addRole('user', 'guest');
        $acl->addRole('editor', 'user');
        $acl->addRole('admin', 'editor');
        
        // 添加默认资源
        $acl->addResource('test');
        $acl->addResource('index');
        $acl->addResource('news');
        $acl->addResource('about');
        $acl->addResource('blog');
        $acl->addResource('community');
        $acl->addResource('page');
        $acl->addResource('category');
        $acl->addResource('user');
        $acl->addResource('home');
        
        // 匿名用户权限
        $acl->deny('guest', null, null); 
        $acl->allow('guest', 
                    array('index', 'about', 'blog', 'community', 'news', 'page', 'user'),
                    array('index')); 
        $acl->allow('guest', 'blog', array('captcha', 'view'));
        $acl->allow('guest', 'community', array('forum', 'topic'));
        $acl->allow('guest', 'page', 'detail');
        $acl->allow('guest', 'user', array('register', 'login', 'reset-password', 'account'));
        
        // 注册用户权限
        $acl->allow('user', 'blog', array('create', 'update', 'delete'));
        $acl->allow('user', 'community', 
                    array('create-topic', 'create-post', 'update-topic', 'update-post'));
        $acl->allow('user', 'user', 
                    array('logout', 'panel', 'info', 'update', 'change-password'));
        
        // 编辑权限
        $acl->allow('editor', 'category', array('home', 'list'));
        $acl->allow('editor', 'community', array('delete-topic', 'delete-post', 'home', 'list-category'));
        $acl->allow('editor', 'page', array('home', 'create', 'update', 'delete', 'list'));
        $acl->allow('editor', 'home', 'home');
        
        // 管理员权限
        $acl->allow('admin', null, null);

        // 当前用户
        $auth = Zend_Auth::getInstance();
        if($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $role = strtolower($identity->role);
        }else{
            $role = 'guest';
        }
        
        $controller = $request->controller;
        $action = $request->action;
        
        if (!$acl->isAllowed($role, $controller, $action)) {
            if ($role == 'guest') {
                $request->setControllerName('user');
                $request->setActionName('login');
            } else {
               $request->setControllerName('error');
               $request->setActionName('noauth');
           }
        }       
        
    }    
}
